﻿using System.Collections.Generic;
using IQIGame.Onigao.GamePlay;
using NetProtocol.POD;

namespace IQIGame.Onigao.Logic
{
    public class BattleUnitController : TController
    {
        public List<Unit> units = new List<Unit>();
        public Dictionary<long, Unit> unitsMap = new Dictionary<long, Unit>();
        private BattlePlayController _playctrl;

        public void Initialize(BattlePlayController playCtrl, CreateBattlePOD rPOD)
        {
            this._playctrl = playCtrl;
        }

        public void OnEnable()
        {
            for (int i = 0; i < this.units.Count; i++)
            {
                var rUnit = this.units[i];
                var rSkillComp = rUnit.GetComponent<SkillComponent>(ETComponentType.SkillComponent);
                rSkillComp.OnEnable();
            }
        }

        public void AddUnit(Unit rUnit)
        {
            if (rUnit != null)
            {
                this.units.Add(rUnit);
                this.unitsMap.TryAdd(rUnit.GUID, rUnit);
                var rTeamCtrl = rUnit.battle.playCtrl.teamCtrl;
                rTeamCtrl.teams[rUnit.teamIndex].units.Add(rUnit);
            }
        }

        public void RemoveUnit(Unit unit)
        {
            if (unit != null)
            {
                unit.Dispose();
                this.units.Remove(unit);
                this.unitsMap.Remove(unit.GUID);

                this._playctrl.resultCtrl.Add(BattleUpdateFactory.CreateRemoveUnit(unit));
            }
        }

        public bool TryGetUnit(long uid, out Unit rUnit)
        {
            return this.unitsMap.TryGetValue(uid, out rUnit);
        }

        public Unit GetUnit(long uid)
        {
            if (this.unitsMap.TryGetValue(uid, out var rUnit))
            {
                return rUnit;
            }

            return null;
        }

        protected override void OnDispose()
        {
            for (int i = 0; i < this.units.Count; i++)
            {
                this.units[i].Dispose();
            }
            this.units.Clear();
            this.unitsMap.Clear();
        }
    }
}